package com.echo.yixiaowu.feature.components

import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.staggeredgrid.LazyStaggeredGridState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 * 滚动连接逻辑
 */
@Composable
fun rememberGridNestedScrollConnection(
    listState: LazyListState,
    gridState: LazyStaggeredGridState,
    isSticky: Boolean,
    coroutineScope: CoroutineScope
): NestedScrollConnection {
    return remember(listState, gridState, isSticky, coroutineScope) {
        object : NestedScrollConnection {
            override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
                val deltaY = available.y
                // 当用户向上滑动，且二级Tab还未吸顶时,且二级Tab内容显示的是第一个
                if (!isSticky && deltaY < 0 && gridState.firstVisibleItemIndex == 0) {
                    // 将滚动事件交给外部的 LazyColumn 处理
                    coroutineScope.launch {
                        listState.scrollBy(-deltaY)
                    }
                    // 消费掉这次滚动，防止内部的Grid滚动
                    return Offset(0f, deltaY)
                }
                // 其他情况（向下滑动，或已经吸顶），让Grid自己处理
                return Offset.Zero
            }
        }
    }
}